package com.wx.freemarker;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import com.wx.util.JsonUtil;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

/**
 * FREEMARKER标签基类
 * 
 * <pre>
 * 在页面使用freemarker自定义函数
 * 步骤一 使用 newTag(beanName) 获取注入spring的bean service;
 * <#assign wxFansUserTag = newTag("articleClassTitleTag") >
 * 步骤二 添加wxFansUserTag 到spring
 * <#assign wxFansUser = wxFansUserTag("")>
 * </pre>
 * 
 * @author dingyaming
 *
 * @param <T>
 */
@Slf4j
public abstract class BaseFreeMarkerTag<T> implements TemplateMethodModelEx {

	@Override
	public Object exec(List jsonParam) throws TemplateModelException {

		try {
			if (jsonParam != null && !jsonParam.isEmpty()) {
				SimpleScalar args1 = (SimpleScalar) jsonParam.get(0);
				String param = args1.getAsString();
				if (param != null) {
					try {
						HashMap jsonObject = JsonUtil.parseObject(param,
								HashMap.class);
						return this.exec(jsonObject);
					} catch (Exception e) {
						log.warn("调用freemarker函数出现异常," + e.getMessage());
						return null;
					}
				} else {
					return this.exec(new HashMap());
				}
			} else {
				return this.exec(new HashMap());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	protected abstract T exec(Map params) throws TemplateModelException;

}
